package com.bite.messageQueue.common;

import java.io.*;

public class BinaryTool{
    /**
     * 序列化
     * @param object 要序列化的对象
     * @return 序列化后的字节数组
     */
    public static byte[] toBytes(Object object) throws IOException {
        try(ByteArrayOutputStream baos = new ByteArrayOutputStream()){
            try(ObjectOutputStream oos = new ObjectOutputStream(baos)) {
                // 将对象写入字节数组输出流
                oos.writeObject(object);
            }
            // 将字节数组输出流转换为字节数组
            return baos.toByteArray();
        }
    }

    /**
     * 反序列化
     * @param bytes 要反序列化的字节数组
     * @return 反序列化后的对象
     */
    public static Object fromBytes(byte[] bytes) throws IOException, ClassNotFoundException {
        Object object = null;
        try (ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes))) {
            // 从字节数组输入流中读取对象
            object = ois.readObject();
        }
        return object;
    }
}
